/*
 *
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *
 *  contributor license agreements. See the NOTICE file distributed with
 *
 *  this work for additional information regarding copyright ownership.
 *
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *
 *  (the "License"); you may not use this file except in compliance with
 *
 *  the License. You may obtain a copy of the License at
 *
 *
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *
 *
 *  Unless required by applicable law or agreed to in writing, software
 *
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 *  See the License for the specific language governing permissions and
 *
 *  limitations under the License.
 *
 * /
 */
package org.apache.kylin.engine.streaming;

import com.esotericsoftware.kryo.Kryo;
import com.google.common.base.Preconditions;
import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.common.streaming.BatchDesc;
import org.apache.kylin.common.streaming.StreamingBatch;
import org.apache.kylin.dimension.Dictionary;
import org.apache.kylin.engine.streaming.util.GapUtils;
import org.apache.kylin.engine.streaming.util.SparkEnv;
import org.apache.kylin.engine.streaming.util.StreamingBatchOptimizer;
import org.apache.kylin.engine.streaming.util.StreamingUtils;
import org.apache.kylin.measure.hllc.HyperLogLogPlusCounter;
import org.apache.kylin.metadata.model.IBuildable;
import org.apache.kylin.metadata.model.TblColRef;
import org.apache.kylin.metadata.realization.RealizationType;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.serializer.KryoRegistrator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.*;

/**
 * 分片builder执行
 */
public class OneOffStreamingMicroBatchBuilder implements Serializable{
    private static final Logger logger = LoggerFactory.getLogger(OneOffStreamingMicroBatchBuilder.class);
    private final RealizationType realizationType;
    private final String realizationName;
    private final String sparkConfPath;
    private static int microCount;
    private transient JavaSparkContext sc;
    private final String kylinHome;
    private transient final IStreamingInput streamingInput;
    private final BatchDesc batchDesc;

    public OneOffStreamingMicroBatchBuilder(RealizationType realizationType,
                                            BatchDesc batchDesc,
                                            String sparkConfPath,
                                            int microCount, String kylinHome) {
        this.batchDesc = batchDesc;
        this.realizationType = Preconditions.checkNotNull(realizationType);
        this.realizationName = Preconditions.checkNotNull(batchDesc.getCubeName());
        this.streamingInput = Preconditions.checkNotNull(StreamingUtils.getStreamingInput());
        this.sparkConfPath = sparkConfPath;
        this.microCount = microCount;
        this.kylinHome = kylinHome;
        KylinConfig.setKylinHome(this.kylinHome);
        sc = SparkEnv.getContext();
        SparkEnv.setConf2Classpath(this.sparkConfPath);
        SparkEnv.addConf2Context(sc,this.sparkConfPath);
    }

    /**
     * 分片build
     * @throws Exception
     */
    public void build() throws Exception {
        StreamingBatch originBatch = streamingInput.getBatchWithTimeWindow(realizationType,batchDesc);
        if (originBatch.isNullBatch()){
            logger.info("batch is null,build exit.");
            sc.close();
            return;
        }
        StreamingBatchOptimizer optimizer = new StreamingBatchOptimizer(originBatch);
        final List<StreamingBatch> microBatchs = optimizer.toMicroBatchs(this.microCount);
        sc.parallelize(microBatchs,microBatchs.size()).foreach(new VoidFunction<StreamingBatch>() {
            private StreamingBatchBuilder streamingBatchBuilder = Preconditions.checkNotNull(StreamingUtils.getMicroBatchBuilder(realizationType, realizationName));
            private IStreamingOutput streamingOutput = Preconditions.checkNotNull(StreamingUtils.getStreamingOutput());

            @Override
            public void call(StreamingBatch batch) throws Exception {
                KylinConfig.setKylinHome(kylinHome);
                IBuildable buildable = streamingBatchBuilder.createBuildable(batch);
                Map<Long, HyperLogLogPlusCounter> samplingResult = streamingBatchBuilder.sampling(batch);
                Map<TblColRef, Dictionary<String>> dictionaryMap = streamingBatchBuilder.buildDictionary(batch, buildable);
                streamingBatchBuilder.build(batch, dictionaryMap, streamingOutput.getCuboidWriter(buildable));
                streamingOutput.output(buildable, samplingResult);
                streamingBatchBuilder.commit(buildable);
            }

        });
        if (batchDesc.isGap()){
            GapUtils.removeFillingTaskLock(realizationName);
        }
        sc.close();
    }
}